import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:management/model/department_model.dart';
import 'package:management/model/visit_matter_model.dart';
import 'package:management/model/visitor_model.dart';
import 'package:management/utils/convert.dart';
import 'package:management/views/visitor/checkIn/idCard_widget.dart';
import 'package:management/utils/log_utils.dart';
import 'package:management/app/cons.dart';
import 'package:management/utils/channel.dart';

Visitor? visitor;

///姓名编辑控制器
TextEditingController _nameController = TextEditingController();

///证件号码编辑控制器
TextEditingController _IDNumberController = TextEditingController();

///联系电话编辑控制器
TextEditingController _telephoneNumController = TextEditingController();

///访客住址编辑控制器
TextEditingController _visitorAddressController = TextEditingController();

///访客单位编辑控制器
TextEditingController _visitorUnitController = TextEditingController();

///访客性别
String _sex = "男";

///民族
String _nationality = "汉";

///出生日期
String _dateOfBirth = '自动生成';

///证件类型
String _typeOfCertificate = '身份证';

///证件号码
// String _IDNumber;

///电话号码
// String _telephoneNum;

///访客住址
// String _visitorAddress;

///访客单位
// String _visitorUnit;

class IDCardRegisterPage extends StatefulWidget {
  @override
  _IDCardRegisterPageState createState() => _IDCardRegisterPageState();
}

class _IDCardRegisterPageState extends State<IDCardRegisterPage>
    with SingleTickerProviderStateMixin {
  static const List<Tab> myTabs = <Tab>[
    Tab(
      text: Strings.visitorInformation,
    ),
    Tab(text: "来访事由"),
  ];

  late TabController _tabController;

  AppBar _buildAppBar(context) => AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          iconSize: 35,
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          "访客登记",
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
        ),
        centerTitle: true,
        backgroundColor: Colors.blue,
        actions: [
          IconButton(
            iconSize: 70,
            onPressed: () {
              Navigator.of(context).pop();
              Navigator.pushNamed(context, '/SearchBlt');
            },
            icon: Image.asset(
              'assets/images/card_reader.png',
              fit: BoxFit.cover,
              width: 100,
              height: 80,
            ),
          ),
          // PopupMenuButton(
          //   offset: Offset(0, 20),
          //   shape: RoundedRectangleBorder(
          //     borderRadius: BorderRadius.circular(0),
          //   ),
          //   icon: Image.asset(
          //     'assets/images/card_reader.png',
          //     fit: BoxFit.cover,
          //     width: 100,
          //     height: 80,
          //     color: Colors.yellow,
          //   ),
          //   itemBuilder: _buildPopMenuItem,
          //   onSelected: (value) async {
          //     MyLog.d("value: $value");
          //     if (value == "蓝牙读卡器") {
          //       Navigator.of(context).pop();
          //       Navigator.of(context).pushNamed('/SearchBlt');
          //     }
          //   },
          // ),
          SizedBox(
            width: 20,
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: myTabs,
          labelStyle: TextStyle(fontSize: 20),
        ),
      );

  //构建读卡器弹出框
  List<PopupMenuEntry> _buildPopMenuItem(BuildContext context) {
    return <PopupMenuEntry<String>>[
      PopupMenuItem(value: "蓝牙读卡器", child: Text("蓝牙读卡器")),
    ];
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: myTabs.length, vsync: this);
  }

  @override
  void dispose() {
    _nameController.text = "";
    _IDNumberController.text = "";
    _telephoneNumController.text = "";
    _visitorAddressController.text = "";
    _visitorUnitController.text = "";
    _dateOfBirth = "自动生成";
    visitor = null;
    SystemChrome.setEnabledSystemUIOverlays([]);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: TabBarView(
        controller: _tabController,
        children: [
          VisitInfo(),
          VisitReason(),
        ],
      ),
    );
  }
}

class VisitInfo extends StatefulWidget {
  @override
  _VisitInfoState createState() => _VisitInfoState();
}

class _VisitInfoState extends State<VisitInfo> {
  ///保存照片的路径
  String _picPath = "";

  ///访客姓名
  // String _name;

  ///出生日期
  // String _birthday;

  ///下方提示
  String _prompt = "读卡器未连接";

  var lastClickTime = DateTime.now();

  ///构建 body
  Widget _buildBody() => SingleChildScrollView(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          color: Colors.black12,
          child: Stack(
            children: [
              Positioned(
                child: Text(
                  "访客信息",
                  style: TextStyle(
                    fontSize: 25,
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                top: 50,
                left: 30,
              ), //左边文字 【访客信息】
              Positioned(
                child: Container(
                  width: 0.9.sw,
                  height: 0.65.sh,
                  padding: EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.grey, width: 2),
                    color: Colors.white,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        width: 1680,
                        height: 250,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              width: 1230,
                              child: Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    height: 50,
                                    // color: Colors.grey,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          "访客姓名",
                                          style: TextStyle(
                                            fontSize: 25,
                                            color: Colors.blue,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        Container(
                                          // alignment: Alignment.bottomLeft,
                                          width: 1100,
                                          child: TextField(
                                            controller: _nameController,
                                            style: TextStyle(
                                                fontSize: 20,
                                                fontWeight: FontWeight.bold),
                                            textAlign: TextAlign.left,
                                            textAlignVertical:
                                                TextAlignVertical.bottom,
                                            inputFormatters: [],
                                            keyboardType: TextInputType.text,
                                            decoration: InputDecoration(
                                              hintText: "请输入姓名",
                                              hintStyle:
                                                  TextStyle(fontSize: 20),
                                              border: OutlineInputBorder(),
                                            ),
                                            onChanged: (name) {
                                              // MyLog.i("访客姓名： $name");
                                            },
                                          ),
                                        ),
                                      ],
                                    ),
                                  ), // 访客姓名
                                  Container(
                                    height: 50,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                         Strings.gender,
                                          style: TextStyle(
                                              fontSize: 25.sp,
                                              color: Colors.blue,
                                              fontWeight: FontWeight.bold),
                                        ),
                                        Container(
                                          width: 1100,
                                          padding: EdgeInsets.only(left: 10),
                                          decoration: BoxDecoration(
                                            border:
                                                Border.all(color: Colors.grey),
                                            borderRadius: BorderRadius.only(
                                              topLeft: Radius.circular(5),
                                              topRight: Radius.circular(5),
                                              bottomLeft: Radius.circular(5),
                                              bottomRight: Radius.circular(5),
                                            ),
                                          ),
                                          child: DropdownButtonHideUnderline(
                                            child: DropdownButton(
                                              value: _sex,
                                              items: [
                                                DropdownMenuItem(
                                                  child: Text(
                                                    "男",
                                                    style: TextStyle(
                                                      fontSize: 20,
                                                      fontWeight:
                                                          FontWeight.bold,
                                                    ),
                                                  ),
                                                  value: "男",
                                                ),
                                                DropdownMenuItem(
                                                  child: Text(
                                                    '女',
                                                    style: TextStyle(
                                                      fontSize: 20,
                                                      fontWeight:
                                                          FontWeight.bold,
                                                    ),
                                                  ),
                                                  value: "女",
                                                ),
                                              ],
                                              onChanged: (v) {
                                                setState(() => _sex = v.toString());
                                              },
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ), //性别
                                  Container(
                                    height: 50,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          "民        族",
                                          style: TextStyle(
                                            fontSize: 25,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        Container(
                                          width: 1100,
                                          decoration: BoxDecoration(
                                            border:
                                                Border.all(color: Colors.grey),
                                            borderRadius: BorderRadius.only(
                                              topLeft: Radius.circular(5),
                                              topRight: Radius.circular(5),
                                              bottomRight: Radius.circular(5),
                                              bottomLeft: Radius.circular(5),
                                            ),
                                          ),
                                          padding: EdgeInsets.only(left: 10),
                                          child: DropdownButtonHideUnderline(
                                            child: DropdownButton(
                                              value: _nationality,
                                              items: _buildMinZuItem(),
                                              onChanged: (value) {
                                                setState(
                                                    () => _nationality = value.toString());
                                              },
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ), //民族
                                  Container(
                                    height: 50,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          "出生日期",
                                          style: TextStyle(
                                            fontSize: 25,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        _buildBirthItem(context),
                                      ],
                                    ),
                                  ), //出生日期
                                ],
                              ),
                            ),
                            VisitorPhoto(
                              400,
                              400,
                              filePath: _picPath,
                            ),
                            //访客相片
                          ],
                        ),
                      ),

                      Container(
                        height: 70,
                        width: 1680,
                        // color: Colors.grey,
                        // alignment: Alignment.topLeft,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              margin: EdgeInsets.only(top: 6.h),
                              // color: Colors.redAccent,
                              // alignment: ,
                              child: Text(
                                "证件类型",
                                style: TextStyle(
                                  fontSize: 25.sp,
                                  color: Colors.blue,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                            Container(
                              width: 680.w,
                              padding: EdgeInsets.only(left: 10.w),
                              decoration: BoxDecoration(
                                border: Border.all(color: Colors.grey),
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(5.w),
                                  topRight: Radius.circular(5.w),
                                  bottomLeft: Radius.circular(5.w),
                                  bottomRight: Radius.circular(5.w),
                                ),
                              ),
                              child: DropdownButtonHideUnderline(
                                child: DropdownButton(
                                  value: _typeOfCertificate,
                                  items: _buildZhengJianItem(),
                                  onChanged: (value) {
                                    setState(() => _typeOfCertificate = value.toString());
                                  },
                                ),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 6.h),
                              child: Text(
                                "证件号码",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  color: Colors.blue,
                                  fontSize: 25.sp,
                                ),
                              ),
                            ),
                            Container(
                              width: 710.w,
                              alignment: Alignment.bottomCenter,
                              // color: Colors.yellow,
                              child: TextField(
                                style: TextStyle(fontSize: 20.sp),
                                textAlign: TextAlign.left,
                                textAlignVertical: TextAlignVertical.bottom,
                                controller: _IDNumberController,
                                keyboardType: TextInputType.number,
                                maxLength: 18,
                                autofocus: false,
                                decoration: InputDecoration(
                                  hintText: "请输入证件号码",
                                  hintStyle: TextStyle(fontSize: 20.sp),
                                  border: OutlineInputBorder(),
                                ),
                                onChanged: (value) {
                                  //xxxxxx19971027xxxx
                                  if (value.length == 18) {
                                    var substring = value.substring(
                                        6, 14); //截取出生日期 19971027
                                    var year = substring.substring(0, 4);
                                    var month = substring.substring(4, 6);
                                    var day = substring.substring(6);
                                    setState(() {
                                      _dateOfBirth = "$year-$month-$day";
                                    });
                                    MyLog.i("$year-$month-$day");
                                  }
                                },
                              ),
                            ),
                          ],
                        ),
                      ), //证件类型
                      Container(
                        width: 1680.w,
                        height: 70.h,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              // color: Colors.grey,
                              padding: EdgeInsets.only(bottom: 20),
                              child: Text(
                                "联系电话",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 25.sp,
                                  color: Colors.blue,
                                ),
                              ),
                            ),
                            Container(
                              width: 1550.w,
                              child: TextField(
                                style: TextStyle(fontSize: 20.sp),
                                textAlign: TextAlign.left,
                                textAlignVertical: TextAlignVertical.bottom,
                                controller: _telephoneNumController,
                                maxLength: 11,
                                decoration: InputDecoration(
                                  border: OutlineInputBorder(),
                                  hintText: "请输入电话号码",
                                  hintStyle: TextStyle(fontSize: 20.sp),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: 1680.w,
                        height: 50.h,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              "访客住址",
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 25.sp),
                            ),
                            Container(
                              width: 1550.w,
                              child: TextField(
                                style: TextStyle(fontSize: 20.sp),
                                textAlign: TextAlign.left,
                                textAlignVertical: TextAlignVertical.bottom,
                                controller: _visitorAddressController,
                                decoration: InputDecoration(
                                    hintText: "请输入访客住址",
                                    hintStyle: TextStyle(fontSize: 20.sp),
                                    border: OutlineInputBorder()),
                              ),
                            )
                          ],
                        ),
                      ), //访客住址
                      Container(
                        height: 50.w,
                        width: 1680.w,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              "访客单位",
                              style: TextStyle(
                                fontSize: 25.w,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            Container(
                              width: 1550.w,
                              child: TextField(
                                style: TextStyle(fontSize: 20.sp),
                                textAlign: TextAlign.left,
                                textAlignVertical: TextAlignVertical.bottom,
                                controller: _visitorUnitController,
                                autofocus: false,
                                decoration: InputDecoration(
                                  hintText: "请输入访客单位",
                                  hintStyle: TextStyle(fontSize: 20.sp),
                                  border: OutlineInputBorder(),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ), // 访客单位
                    ],
                  ),
                ),
                top: 15.h,
                right: 15.w,
              ), // 右边内容
              Positioned(
                bottom: 200.h,
                right: 500.w,
                left: 500.w,
                child: Container(
                  child: MaterialButton(
                    height: 60,
                    color: Colors.blue,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(50)),
                    ),
                    onPressed: () {
                      intervalClick();
                    },
                    child: Text(
                      _prompt,
                      style: TextStyle(color: Colors.white, fontSize: 35),
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: 180,
                // right: 300,
                left: 858,
                child: BluetoothChannel.isConnectedDevice
                    ? Text("请先连接读卡器再点击读卡按钮")
                    : Text(""),
              ) //下方提示
            ],
          ),
        ),
      );

  //构建民族的选项
  List<DropdownMenuItem<String>>? _buildMinZuItem() => Cons.nationality
      .map((e) => DropdownMenuItem(
            child: Text(
              e,
              style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
            ),
            value: e,
          ))
      .toList();

  //构建出生日期
  Widget _buildBirthItem(BuildContext context) => Container(
        width: 1100.w,
        child: Text(
          _dateOfBirth,
          style: TextStyle(
            fontSize: 20.sp,
          ),
        ),
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 10.w),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(5.w),
            topRight: Radius.circular(5.w),
            bottomRight: Radius.circular(5.w),
            bottomLeft: Radius.circular(5.w),
          ),
        ),
      );

  //构建证件类型
  List<DropdownMenuItem<String>> _buildZhengJianItem() => Cons.zhengJianLeiXing
      .map((e) => DropdownMenuItem(
            value: e,
            child: Text(
              e,
              style: TextStyle(fontSize: 20.sp, fontWeight: FontWeight.bold),
            ),
          ))
      .toList();

  @override
  void initState() {
    super.initState();
    BluetoothChannel.bluetoothChannel!.setMessageHandler((message) {
      if (message is Map) {
        if (message["method"] == "receiveIDCardMsg") {
          if (message['retCode'] != 1) {
            Fluttertoast.showToast(msg: "读卡失败!");
            return Future.error("error");
          }
          setState(() {
            _nameController.text = message["partyName"];
            _sex = message["gender"];
            _nationality = message["nation"];
            if (!TextUtil.isEmpty(message['bornDay'])) {
              // _birthday = DateUtil.formatDateStr(message["bornDay"],
              //     format: 'yyyy-MM-dd');
              _dateOfBirth = DateUtil.formatDateStr(message["bornDay"],
                  format: 'yyyy-MM-dd');
            }
            _typeOfCertificate = "身份证";
            _IDNumberController.text = message["certNumber"];
            _visitorAddressController.text = message["certAddress"];
            _picPath = message["picPath"];
          });
        }

        if (message["method"] == "connectState") {
          bool connect = message["connectState"];
          connect
              ? BluetoothChannel.isConnectedDevice = true
              : BluetoothChannel.isConnectedDevice = false;
          Fluttertoast.showToast(msg: connect ? "连接成功" : "连接失败");
        }
      }
      MyLog.w("message : ${message.toString()}");
      return Future.error("error");
    });
  }

  @override
  Widget build(BuildContext context) {
    if (BluetoothChannel.isConnectedDevice &&
        BluetoothChannel.isOpenBluetooth) {
      _prompt = "读卡";
    }
    return _buildBody();
  }

  //防止多次点击
  void intervalClick() {
    if (DateTime.now().difference(lastClickTime) < Duration(seconds: 2)) {
      // print("不能多次点击");
      return;
    } else {
      lastClickTime = DateTime.now();
    }
    if (BluetoothChannel.isConnectedDevice) {
      try {
        receiveMessage();
      } on Exception {} catch (e) {
        print(e);
      }
    }
  }

  ///接收蓝牙读卡器数据
  void receiveMessage() async {
    await BluetoothChannel.bluetoothChannel!.send("receiveMessage");
  }
}

class VisitReason extends StatefulWidget {
  @override
  _VisitReasonState createState() => _VisitReasonState();
}

class _VisitReasonState extends State<VisitReason> {
  TextEditingController _textEditingControllerInterviewee =
      TextEditingController();
  TextEditingController _textEditingControllerRemark = TextEditingController();
  TextEditingController _textEditingControllerWhatToBring =
      TextEditingController();
  TextEditingController _textEditingControllerLicensePlateNumber =
      TextEditingController();
  TextEditingController _textEditingControllerNumberOfAccompanyingVisitors =
      TextEditingController();
  TextEditingController _textEditingControllerRegistrationPoint =
      TextEditingController();
  TextEditingController _textEditingControllerDate = TextEditingController();
  TextEditingController _textEditingControllerDateTime =
      TextEditingController();
  String _department = "行政部";

  String _matter = "面试";

  String _currentDate = Convert.currentDate();
  String _currentDateTime = Convert.currentDateTime(second: false);
  Visitor? visitor;
  List<Department>? departments = [];
  List<VisitMatter>? matters = [];

  FocusNode focusNode = FocusNode();

  //被访人历史记录
  List<String>? interviewees = [];

  @override
  void initState() {
    _textEditingControllerRegistrationPoint.text = SpUtil.getString(
        Strings.sp_key_registrationPoint,
        defValue: Strings.sp_defaultValue_registrationPoint)!;
    queryDepartmentAndVisitMatter();
    // queryInterviewee();
    super.initState();
  }

  Widget _buildBody(context) => SingleChildScrollView(
        child: Container(
          width: 1.sw,
          height: 1.sh,
          color: Colors.black12,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                padding: EdgeInsets.all(20.w),
                width: 1.sw,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "被   访  人",
                      style: TextStyle(
                        fontSize: 25.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Container(
                      width: 0.9.sw,
                      height: 0.1.sh,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12.w),
                          border: Border.all(color: Colors.grey, width: 2.w),
                          color: Colors.white),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Container(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                Text(
                                  "被访部门",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 25.sp,
                                  ),
                                ),
                                Container(
                                  padding: EdgeInsets.only(left: 10.w),
                                  height: 50.h,
                                  width: 700.w,
                                  decoration: BoxDecoration(
                                    border: Border.all(color: Colors.grey),
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(5.w),
                                      topRight: Radius.circular(5.w),
                                      bottomLeft: Radius.circular(5.w),
                                      bottomRight: Radius.circular(5.w),
                                    ),
                                  ),
                                  child: DropdownButtonHideUnderline(
                                    child: DropdownButton(
                                      hint: Text(
                                        "请选择被访部门",
                                        style: TextStyle(fontSize: 20),
                                      ),
                                      value: _department,
                                      items: departments!
                                          .map((e) => DropdownMenuItem(
                                              value: e.name,
                                              child: Text(
                                                e.name!,
                                                style: TextStyle(
                                                    fontSize: 20,
                                                    fontWeight:
                                                        FontWeight.bold),
                                              )))
                                          .toList(),
                                      onChanged: (value) {
                                        MyLog.d("被访部门：$value");
                                        setState(() => _department = value.toString());
                                      },
                                    ),
                                  ),
                                ),
                                Text(
                                  "被  访  人",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 25,
                                  ),
                                ),
                                Container(
                                  width: 700.w,
                                  height: 50.h,
                                  child: Row(
                                    children: [
                                      SizedBox(
                                        width: 500,
                                        child: TextField(
                                          controller:
                                              _textEditingControllerInterviewee,
                                          style: TextStyle(
                                            fontSize: 20,
                                          ),
                                          textAlign: TextAlign.left,
                                          textAlignVertical:
                                              TextAlignVertical.bottom,
                                          focusNode: focusNode,
                                          decoration: InputDecoration(
                                            hintText: "请输入被访人姓名",
                                            hintStyle: TextStyle(fontSize: 20),
                                            border: OutlineInputBorder(),
                                          ),
                                        ),
                                      ),
                                      TextButton(
                                        onPressed: () {
                                          showDateChoose();
                                        },
                                        child: Text("历史记录"),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ), //被访人
              Container(
                width: MediaQuery.of(context).size.width,
                padding: EdgeInsets.only(left: 20, right: 20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "访问事由",
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                    ),
                    Container(
                      width: 0.9.sw,
                      height: 0.1.sh,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12.w),
                          border: Border.all(color: Colors.grey, width: 2.w),
                          color: Colors.white),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Text(
                            "来访事项",
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 25.sp),
                          ),
                          Container(
                            padding: EdgeInsets.only(left: 10.w),
                            height: 50.h,
                            width: 700.w,
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(5.w),
                                topRight: Radius.circular(5.w),
                                bottomLeft: Radius.circular(5.w),
                                bottomRight: Radius.circular(5.w),
                              ),
                            ),
                            child: DropdownButtonHideUnderline(
                              child: DropdownButton(
                                hint: Text(
                                  "请选择来访事项",
                                  style: TextStyle(fontSize: 20),
                                ),
                                value: _matter,
                                items: matters!
                                    .map((e) => DropdownMenuItem(
                                        value: e.matter,
                                        child: Text(
                                          e.matter!,
                                          style: TextStyle(
                                              fontSize: 20.sp,
                                              fontWeight: FontWeight.bold),
                                        )))
                                    .toList(),
                                onChanged: (value) {
                                  MyLog.d("来访事项：$value");
                                  setState(() => _matter = value.toString());
                                },
                              ),
                            ),
                          ),
                          Text(
                            "备        注",
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 25),
                          ),
                          Container(
                            width: 700.w,
                            height: 50.h,
                            child: TextField(
                              style: TextStyle(fontSize: 18.sp),
                              textAlign: TextAlign.left,

                              // textAlignVertical: TextAlignVertical.bottom,
                              controller: _textEditingControllerRemark,
                              decoration: InputDecoration(
                                hintStyle: TextStyle(fontSize: 18),
                                border: OutlineInputBorder(),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              ), //访客事由
              Container(
                width: 1.sw,
                padding: EdgeInsets.only(left: 20, right: 20, top: 20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '登记情况',
                      style: TextStyle(
                          fontSize: 25.sp, fontWeight: FontWeight.bold),
                    ),
                    Container(
                      width: 0.9.sw,
                      height: 0.3.sh,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12.w),
                          border: Border.all(color: Colors.grey, width: 2.w),
                          color: Colors.white),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Text(
                                "携带物品",
                                style: TextStyle(
                                    fontSize: 25, fontWeight: FontWeight.bold),
                              ),
                              Container(
                                width: 700.w,
                                height: 50.h,
                                child: TextField(
                                  controller: _textEditingControllerWhatToBring,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  style: TextStyle(fontSize: 25),
                                  decoration: InputDecoration(
                                    hintText: "请输入携带物品",
                                    hintStyle: TextStyle(fontSize: 20.sp),
                                    border: OutlineInputBorder(),
                                  ),
                                ),
                              ),
                              Text(
                                "车牌号码",
                                style: TextStyle(
                                    fontSize: 25.sp,
                                    fontWeight: FontWeight.bold),
                              ),
                              Container(
                                width: 700.w,
                                height: 50.h,
                                child: TextField(
                                  controller:
                                      _textEditingControllerLicensePlateNumber,
                                  style: TextStyle(fontSize: 18.sp),
                                  textAlignVertical: TextAlignVertical.bottom,
                                  decoration: InputDecoration(
                                      hintText: "请输入车牌号码",
                                      hintStyle: TextStyle(fontSize: 20.sp),
                                      border: OutlineInputBorder()),
                                ),
                              )
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Text("随行访客",
                                  style: TextStyle(
                                      fontSize: 25.sp,
                                      fontWeight: FontWeight.bold)),
                              Container(
                                width: 700.w,
                                height: 50.h,
                                child: TextField(
                                  controller:
                                      _textEditingControllerNumberOfAccompanyingVisitors,
                                  style: TextStyle(fontSize: 18.sp),
                                  textAlignVertical: TextAlignVertical.bottom,
                                  decoration: InputDecoration(
                                      hintText: "请输入随行访客人数",
                                      hintStyle: TextStyle(fontSize: 20.sp),
                                      border: OutlineInputBorder()),
                                ),
                              ),
                              Text(
                                "登  记  点",
                                style: TextStyle(
                                    fontSize: 25.sp,
                                    fontWeight: FontWeight.bold),
                              ),
                              Container(
                                width: 700.w,
                                height: 50.h,
                                child: TextField(
                                  controller:
                                      _textEditingControllerRegistrationPoint,
                                  style: TextStyle(fontSize: 18.sp),
                                  textAlignVertical: TextAlignVertical.bottom,
                                  decoration: InputDecoration(
                                    hintText: '请输入登记点',
                                    hintStyle: TextStyle(fontSize: 20.sp),
                                    border: OutlineInputBorder(),
                                  ),
                                ),
                              )
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Text(
                                "登记日期",
                                style: TextStyle(
                                    fontSize: 25.sp,
                                    fontWeight: FontWeight.bold),
                              ),
                              Container(
                                width: 700.w,
                                height: 50.h,
                                child: TextField(
                                  controller: _textEditingControllerDate,
                                  readOnly: false,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  style: TextStyle(fontSize: 20.sp),
                                  decoration: InputDecoration(
                                      hintText: _currentDate,
                                      hintStyle: TextStyle(fontSize: 20.sp),
                                      border: OutlineInputBorder()),
                                ),
                              ),
                              Text(
                                "时        间",
                                style: TextStyle(
                                    fontSize: 25.sp,
                                    fontWeight: FontWeight.bold),
                              ),
                              Container(
                                width: 700.w,
                                height: 50.h,
                                child: TextField(
                                  controller: _textEditingControllerDateTime,
                                  readOnly: false,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  style: TextStyle(fontSize: 20.sp),
                                  decoration: InputDecoration(
                                    hintText: _currentDateTime,
                                    hintStyle: TextStyle(fontSize: 20.sp),
                                    border: OutlineInputBorder(),
                                  ),
                                ),
                              )
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ), //登记情况
              SizedBox(
                height: 50,
              ),
              _buildConfirmButton(),
            ],
          ),
        ),
      );

  //显示被访人历史记录
  void showIntervieweeHistory() async {
    var name = await showMenu(
      context: context,
      position: RelativeRect.fromLTRB(500, 190, 120, 100),
      items: interviewees!
          .map(
            (e) => PopupMenuItem(
              value: e,
              child: Text(e),
            ),
          )
          .toList(),
    );

    _textEditingControllerInterviewee.text = name!;

    MyLog.i("name: $name");
  }

  ///显示时间段选择
  void showDateChoose() async {
    var choose = await showMenu(
      context: context,
      position: RelativeRect.fromLTRB(500, 190, 120, 100),
      items: [
        PopupMenuItem(
          child: Text("最近一个月"),
          value: 1,
        ),
        PopupMenuItem(
          child: Text("最近两个月"),
          value: 2,
        ),
        PopupMenuItem(
          child: Text("最近三个月"),
          value: 3,
        ),
      ],
    );
    if (choose != null) {
      switch (choose) {
        case 1:
          interviewees = await VisitorProvider.provider.queryInterviewee(1);
          break;
        case 2:
          interviewees = await VisitorProvider.provider.queryInterviewee(2);
          break;
        case 3:
          interviewees = await VisitorProvider.provider.queryInterviewee(3);
          break;
      }
      showIntervieweeHistory();
    }
    MyLog.i("choose: $choose");
  }

  //确认
  Widget _buildConfirmButton() => MaterialButton(
        minWidth: 300,
        height: 50,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.horizontal(
            left: Radius.circular(50),
            right: Radius.circular(50),
          ),
        ),
        child: Text(
          "完成",
          style: TextStyle(color: Colors.white, fontSize: 30),
        ),
        color: Colors.blue,
        onPressed: () {
          var name = _nameController.text;
          if (TextUtil.isEmpty(name)) {
            Fluttertoast.showToast(msg: "姓名不能为空");
            return;
          }
          var idNumber = _IDNumberController.text;
          if (TextUtil.isEmpty(idNumber) ||
              (_typeOfCertificate == "身份证" && idNumber.length != 18)) {
            Fluttertoast.showToast(msg: "请填写正确的证件号码");
            return;
          }
          var telephoneNum = _telephoneNumController.text;

          if (TextUtil.isEmpty(telephoneNum) || telephoneNum.length != 11) {
            Fluttertoast.showToast(msg: "请填写正确的手机号");
            return;
          }

          var visitorAddress = _visitorAddressController.text;
          var visitorUnit = _visitorUnitController.text;
          var interviewee = _textEditingControllerInterviewee.text;
          var remark = _textEditingControllerRemark.text;
          var whatToBring = _textEditingControllerWhatToBring.text;
          var licensePlateNumber =
              _textEditingControllerLicensePlateNumber.text;
          var numberOfAccompanyingVisitors =
              _textEditingControllerNumberOfAccompanyingVisitors.text;
          var registrationPoint = _textEditingControllerRegistrationPoint.text;
          var registerDate = _textEditingControllerDate.text;
          var registerTime = _textEditingControllerDateTime.text;
          visitor = Visitor(
            name,
            _sex,
            _typeOfCertificate,
            idNumber,
            nationality: _nationality,
            dateOfBirth: _dateOfBirth,
            visitorAddress: TextUtil.isEmpty(visitorAddress)
                ? Strings.nothing
                : visitorAddress,
            telephoneNum: telephoneNum,
            visitorUnit:
                TextUtil.isEmpty(visitorUnit) ? Strings.nothing : visitorUnit,
            departmentInterviewed: _department,
            interviewee:
                TextUtil.isEmpty(interviewee) ? Strings.nothing : interviewee,
            visitingMatters: _matter,
            remarks: TextUtil.isEmpty(remark) ? Strings.nothing : remark,
            whatToBring:
                TextUtil.isEmpty(whatToBring) ? Strings.nothing : whatToBring,
            licensePlateNumber: TextUtil.isEmpty(licensePlateNumber)
                ? Strings.nothing
                : licensePlateNumber,
            numberOfAccompanyingVisitors:
                TextUtil.isEmpty(numberOfAccompanyingVisitors)
                    ? Strings.nothing
                    : numberOfAccompanyingVisitors,
            registrationPoint: registrationPoint,
            registrationDate:
                TextUtil.isEmpty(registerDate) ? _currentDate : registerDate,
            checkInTime: TextUtil.isEmpty(registerTime)
                ? _currentDateTime
                : registerTime,
          );
          // Navigator.pop(context);
          VisitorProvider.provider.insert(visitor!);
          Fluttertoast.showToast(msg: "登记完成");
          MyLog.d("visitor: ${visitor!.toMap()}");
          SystemChrome.setEnabledSystemUIOverlays([]);
          Navigator.pop(context);
        },
      );

  @override
  Widget build(BuildContext context) {
    return _buildBody(context);
  }

  void queryDepartmentAndVisitMatter() async {
    departments = await DepartmentProvider().queryAll();
    if (departments == null) {
      departments = [];
    }
    matters = await VisitMatterProvider().queryAll();
    if (matters == null) {
      matters = [];
    }
    setState(() {});
  }

  void queryInterviewee() async {
    MyLog.i("Interviewee: ${interviewees.toString()}");
  }
}
